package com.tim.helper.string;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.CharSetUtils;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.junit.Test;
import org.springframework.util.CollectionUtils;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description:
 * @Version 1.0, 2021/6/17
 * @Author Tim
 */
public class HtmlHelper {

    @Test
    public void getHtmlText() throws IOException {
        String html = "" +
				"";
        if(StringUtils.isBlank(html)){
        	html = Files.readAllLines(Paths.get("C:\\Users\\Administrator\\Desktop\\test.txt"))
					.stream()
					.collect(Collectors.joining());
		}
        String enterFlag = "ENTER_BUTTON";
        html = html.replaceAll("<", enterFlag+"<");
        Document doc = Jsoup.parseBodyFragment(html);
        Element body = doc.body();
		String text = body.text()
				.replaceAll(enterFlag, "\n")
				.replaceAll("\n\\s+", "\n");
		System.out.println(text);

    }

    @Test
    public void runJsCode() throws Exception {
    	String[] infos = {
    			// 一期
    			"懒猪快送/懒猪快送-用户端/20210325/懒猪C端APP0325", //0
    			"懒猪快送/懒猪骑士/20210302/懒猪骑士0302", //1
    			// 二期；二期包含一期内容
    			"懒猪二期/用户端/20210603" //2
    			,"懒猪二期/骑士APP/20210508" //3
    	};
    	String info = infos[2];
    	String resultAttrName = "sitemap.rootNodes";// sitemap.rootNodes
        String childrenAttrName = "children";
        String menuAttrName = "pageName";
        if(CharSetUtils.count(info, "%")<6){
    		// url编码
        	info = URLEncoder.encode(info);
    	}
    	String template = "https://yxt-release.lazipig.com/%s/data/document.js";
        String jsCode = HttpUtil.get(String.format(template, info));
        int quoteIdx = jsCode.trim().indexOf('(');
        if(quoteIdx!=0){
        	jsCode = jsCode.substring(quoteIdx+1, jsCode.lastIndexOf(')'));
        }
        ScriptEngineManager mgr=new ScriptEngineManager();
        ScriptEngine engine=mgr.getEngineByName("javascript");
        Object obj = engine.eval(jsCode);
        System.out.println();
        String jsonStr = JSON.toJSONString(obj);
        List<String> content = doPrintXmindTree(jsonStr, resultAttrName, childrenAttrName, menuAttrName);
        if(num<3){
        	// 修改菜单层级
        	num = 0;
        	content.remove(0);
        	for (int i = 0; i < content.size(); i++) {
				String item = content.get(i);
				item = item.replaceFirst("\t", "");
				if(!item.startsWith("\t")){
					item = (num++)+"，"+item;
				}
				content.set(i, item);
			}
        }
		content.forEach(System.out::println);
    }
    
    public List<String> doPrintXmindTree(String jsonStr, String resultAttrName, String childrenAttrName, String menuAttrName) {
		List<String> content = new ArrayList<>();// 结果

		JSONObject json = JSON.parseObject(jsonStr);
		resultAttrName = resultAttrName.trim();
		int dotIndex = resultAttrName.indexOf('.');
		if(dotIndex>-1){
			String[] strs = resultAttrName.split("\\.");
			resultAttrName = strs[strs.length-1];
			for (int i = 0; i < strs.length-1; i++) {
				json = json.getJSONObject(strs[i]);
			}
		}
		JSONObject menuList = json.getJSONObject(resultAttrName);
		handle(childrenAttrName, menuAttrName, "", content, menuList);
		return content;
	}

    // 排除部分无用项
    List<String> excludes = Arrays.asList("修订历史", "业务流程", "异常上报", "异常上报流程", 
    		"派单逻辑", "归属逻辑", "协议更新");
    int num = 0;
	private void handle(String childrenAttrName, String menuAttrName, String padding, List<String> content, JSONObject menuList) {
		for (int i = 0; i < menuList.size(); i++) {
			String key = String.valueOf(i);
			if(!menuList.containsKey(key)){
				return;
			}
			JSONObject menu = menuList.getJSONObject(""+i);
			String menuName = menu.getString(menuAttrName)
					.replace("-增", "")
					.replace("-改", "")
					.replaceAll("\\(\\d\\)", "")
					.trim();
			if(excludes.contains(menuName.length()<5?menuName:menuName.substring(0, 4))){
				continue;
			}
			// 加入菜单，递归处理子项
			content.add(("".equals(padding)?(num++)+"，":padding)+menuName);
			JSONObject children = menu.getJSONObject(childrenAttrName);
			if(!CollectionUtils.isEmpty(children)){
				handle(childrenAttrName, menuAttrName, padding+"\t", content, children);
			}

		}
	}
}
